/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: just
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: Jun 12, 2011 4:54:08 PM
 *
*/ 
package org.justframework.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * route request to the right resource
 *
 */
public class RequestRouter {
	private static Map<String,Class<ResourceService>> routeMap = new HashMap<String,Class<ResourceService>>();
	
	private static List<PathPattern> routeRules = new ArrayList();
	
	/**
	 * attach route rules
	 * @param pathTemplate
	 * @param resource
	 */
	public static void attach(String pathTemplate, Class resource) {
		routeMap.put(pathTemplate, resource);
		routeRules.add(new PathPattern(pathTemplate));
		Collections.sort(routeRules);
	}
	
	/**
	 * locate resource by uri
	 * @param request
	 * @return
	 */
	public static Class locate(String path, Map<String,String> urlParams) {
		String pathTemplate = matchPath(path,urlParams);
		Class<ResourceService> klass = routeMap.get(pathTemplate);
		return klass;
	}

	/**
	 * match and parse uri path
	 * @param path
	 * @param urlParams
	 * @return
	 */
	private static String matchPath(String path, Map<String,String> urlParams){
		String target = "";	
		for(PathPattern p:routeRules){
			Matcher matcher = Pattern.compile(p.getPattern()).matcher(path);
			if(matcher.matches()){
				target = p.getPath();
				if(p.getParamNames() != null && p.getParamNames().size()>0){
					for(int i=0;i<p.getParamNames().size();i++){
						urlParams.put(p.getParamNames().get(i), matcher.group(i+1));
					}
				}
				break;
			}
		}
		return target;
	}
	
}
